const express = require("express");
const { db } = require("../database");


// 创建路由对象，使得用户登录状态检查的中间件只作用于部分路由。
const router = express.Router();
//有没有登录
const { useAuthorization } = require("./base");
router.use(useAuthorization);

//查询申请会议室信息
router.get("/", async (req, res) => {
    const meeting = await db.select`SELECT * FROM meetingroomapply`;
    res.send({
        code: 200,
        message: "查询申请会议室成功",
        result: meeting
    })
})
//添加申请会议室的信息
.post("/post", async (req, res) => {
        const { meetroomid,begindate, enddate, applyreason, status } = req.body;
        const apply = await db.insert(
            "insert into meetingroomapply (meetroomid, begindate, enddate, applyreason,status) values (?,?, ?, ?,1)",
            [meetroomid,begindate, enddate, applyreason, status]
        );
        const meet = await db.findOne`select * from meetingroomapply where id = ${apply}`;
        res.send({
            code: 200,
            message: "申请会议室成功",
            result: meet
        });
    })

//修改申请的会议室的信息
.put("/apply/:tid",
async(req,res)=>{
  const message= await db.findOne`select * from meetingroomapply where id = ${req.params.tid}`;
  console.log(req.params.tid);
  if(!message){
    return res.send({
      code:-1,
      message:"该会议室信息不存在！"
    })
  }
  const { begindate, enddate, applyreason,status } = req.body;
 await db.run`update meetingroomapply set begindate = ${begindate}, enddate = ${enddate}, applyreason = ${applyreason},status=${status} where id = ${req.params.tid}`;
 const meets=await db.findOne`select * from meetingroomapply where id = ${req.params.tid}`;
 res.send({
  code:200,
  message:"会议室修改成功",
  result:meets
 });
})
//删除会议室的信息
.delete("/dele/:tid",
async (req,res)=>{
  const room=
  await db.findOne`select * from meetingroomapply where id = ${req.params.tid}`
  if(!room){
    return res.send({
      code:-1,
      message:"该会议室信息不存在！"
    })
  }
 await db.run `delete from meetingroomapply where id = ${req.params.tid}`
 res.send({
  code:200,
  message:"删除成功",
 })
}
)
//
// 将路由作为中间件挂接在 / 根路由上。
const registerRouter = (app) => app.use("/meetingroomapply", router);

module.exports = { registerRouter };